<template>
  <div class="home-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="店家名称">
              <el-input v-model="queryParams.shopName" placeholder="输入店家名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input v-model="queryParams.keyword" placeholder="地址/描述关键字" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select
                  v-model="queryParams.tagIds"
                  multiple
                  placeholder="选择标签"
                  clearable
              >
                <el-option
                    v-for="tag in tagList"
                    :key="tag.id"
                    :label="tag.label"
                    :value="tag.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市" >
              <el-select
                  v-model="queryParams.cityId"
                  placeholder="选择城市"
                  clearable>
                <el-option
                    v-for="city in cityOptions"
                    :key="city.id"
                    :label=getCityName(city.id)
                    :value="city.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="loadShops">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 店家列表 -->
    <div class="shop-list">
      <el-row :gutter="20">
        <el-col
            v-for="shop in shopList"
            :key="shop.id"
            :xs="24" :sm="12" :md="8" :lg="6" :xl="4"
        >
          <el-card class="shop-card" @click="goToDetail(shop.id)">
            <div class="shop-status" :class="shop.status === '1' ? 'active' : 'inactive'">
              {{ shop.status === '1' ? '营业中' : '已歇业' }}
            </div>
            <div class="shop-header">
              <el-image
                  :src="shop.logoImgUrl"
                  class="shop-logo"
                  fit="cover"
              >
                <template #error>
                  <div class="image-error">LOGO</div>
                </template>
              </el-image>
              <h3 class="shop-name">{{ shop.shopName }}</h3>
            </div>

            <div class="shop-info">
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span>{{ shop.address }}</span>
              </div>
              <div class="info-item">
                <el-icon><OfficeBuilding /></el-icon>
                <span>{{ getCityName(shop.cityId) }}</span>
              </div>
              <div class="info-item tags">
                <el-tag
                    v-for="tag in shop.tagIdList"
                    :key="tag"
                    type="info"
                    size="small"
                >
                  {{ getTagLabel(tag) }}
                </el-tag>
              </div>
            </div>

            <div class="shop-footer">
              <el-rate
                  v-model="shop.avgRating"
                  disabled
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              />
              <span class="rating-text">{{ shop.avgRating.toFixed(1) }}</span>
              <span class="order-num">月售{{ shop.orderNum }}单</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="loadShops"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Location, OfficeBuilding } from '@element-plus/icons-vue'
import qs from 'qs'
import router from "@/router";

// 查询参数
const queryParams = ref({
  shopName: '',
  keyword: '',
  status: '',
  tagIds: [],
  cityId: '',
  pageNum: 1,
  pageSize: 12
})

// 数据列表
const shopList = ref([])
const total = ref(0)
const tagList = ref([])
const cityOptions = ref([])

// 获取标签列表
const loadTags = async () => {
  try {
    const res = await axios.get(BASE_URL+'/v1/show/tag/select')
    if (res.data.code === 2000) {
      tagList.value = res.data.data
      console.log(tagList.value)
    }
  } catch (error) {
    ElMessage.error('标签加载失败')
  }
}

// 获取城市数据
const loadCities = async () => {
  try {
    const res = await axios.get(BASE_URL+'/v1/show/area/select', {
      params: {
        depth: 2 // 获取二级城市数据
      }
    })
    if (res.data.code === 2000) {
      cityOptions.value = processCityData(res.data.data)
    }
  } catch (error) {
    ElMessage.error('城市数据加载失败')
  }
}

// 处理城市数据格式
const processCityData = (data) => {
  return data.map(item => ({
    ...item,
    children: item.children || []
  }))
}

// 获取店铺列表
const loadShops = async () => {
  try {
    const params = {
      ...queryParams.value,
      tagIds: queryParams.value.tagIds.join(',')
    }
    const res = await axios.get(BASE_URL+'/v1/show/shop/select',{ params})
    if (res.data.code === 2000) {
      shopList.value = res.data.data
      total.value = res.data.data.total
      console.log(shopList.value)
    }
  } catch (error) {
    ElMessage.error('店铺加载失败')
  }
}

// 标签ID转名称
const getTagLabel = (tagId) => {
  const tag = tagList.value.find(t => t.id === tagId)
  return tag?.label || '未知标签'
}

// 城市编码转名称
const getCityName = (cityId) => {
  const findCity = (list) => {
    for (const city of list) {
      if (city.id === cityId) return city
      if (city.children?.length) {
        const found = findCity(city.children)
        if (found) return found
      }
    }
    return null
  }
  return findCity(cityOptions.value)?.name || '未知城市'
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    shopName: '',
    keyword: '',
    status: '',
    tagIds: [],
    cityId: '',
    pageNum: 1,
    pageSize: 12
  }
  loadShops()
}

onMounted(() => {
  loadTags()
  loadCities()
  loadShops()
})

const goToDetail = (shopId) => {
  location.href = `/shop/detail/${shopId}`
}
</script>

<style scoped>
.home-container {
  padding: 20px;
  background: #f5f7fa;
}

.filter-card {
  margin-bottom: 20px;
}

.shop-list {
  min-height: 600px;
}

.shop-card {
  position: relative;
  margin-bottom: 20px;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.shop-status {
  position: absolute;
  right: 10px;
  top: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;

  &.active {
    background: #e1f3d8;
    color: #67c23a;
  }
  &.inactive {
    background: #fde2e2;
    color: #f56c6c;
  }
}

.shop-header {
  text-align: center;
  padding: 10px 0;

  .shop-logo {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: 10px;
  }

  .shop-name {
    margin: 0;
    font-size: 16px;
    color: #303133;
  }
}

.shop-info {
  padding: 10px 0;

  .info-item {
    display: flex;
    align-items: center;
    margin: 8px 0;
    font-size: 13px;
    color: #606266;

    .el-icon {
      margin-right: 8px;
      font-size: 16px;
    }

    &.tags {
      flex-wrap: wrap;
      gap: 4px;
    }
  }
}

.shop-footer {
  display: flex;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;

  .rating-text {
    margin-left: 8px;
    color: #f7ba2a;
    font-weight: bold;
  }

  .order-num {
    margin-left: auto;
    color: #909399;
    font-size: 12px;
  }
}

.image-error {
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>